package com.mmd.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.mmd.common.entity.MmdArea;
import com.mmd.manage.dao.AreaDao;
import com.mmd.manage.dao.RouteDetailDao;
import com.mmd.manage.service.FeeService;
import com.mmd.manage.vo.FeeInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class FeeServiceImpl implements FeeService{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RouteDetailDao routeDetailDao;
	@Autowired
	private AreaDao areaDao;
	
	@Override
	public List<FeeInfoVo> computeTotalFee(Float weight, Long areaId, Long modeId, String hscode, Integer type) {
		List<FeeInfoVo> feeInfoList = routeDetailDao.computeTotalFee(weight, areaId, modeId, hscode);
		logger.info("#########{}", JSON.toJSONString(feeInfoList));
		for (FeeInfoVo vo : feeInfoList){
			//0-非独清关, 1-单独清关
			//非独总计=重量*单价+重量*附加费+单票操作费
			//单独清关总计=重量*单价+重量*附加费+单票操作费+重量*中港+单票报关费
			BigDecimal weightSinglePrice = new BigDecimal(weight).multiply(vo.getSinglePrice() == null ?  BigDecimal. ZERO : vo.getSinglePrice()).setScale(2, RoundingMode.HALF_UP);
			BigDecimal weightAttachFee = new BigDecimal(weight).multiply(vo.getAttachFee() == null ? BigDecimal. ZERO : vo.getAttachFee()).setScale(2, RoundingMode.HALF_UP);
			BigDecimal totalFee = weightSinglePrice.add(weightAttachFee).add(vo.getSingleOperatFee() == null ? BigDecimal. ZERO : vo.getSingleOperatFee());

			if (type == 1){
				BigDecimal weightZgFee = new BigDecimal(weight).multiply(vo.getZgFee() == null ?  BigDecimal. ZERO : vo.getZgFee()).setScale(2, RoundingMode.HALF_UP);
				totalFee = totalFee.add(weightZgFee).add(vo.getSingleDeclareFee() == null ?  BigDecimal. ZERO : vo.getSingleDeclareFee());
			}
			vo.setTotalFee(totalFee);
		}
		//正序排列
		Collections.sort(feeInfoList, new Comparator<FeeInfoVo>() {

			@Override
			public int compare(FeeInfoVo o1, FeeInfoVo o2) {
				BigDecimal totalFee1 = o1.getTotalFee();
				BigDecimal totalFee2 = o2.getTotalFee();
				return totalFee1.compareTo(totalFee2);
			}
			
		});
		return feeInfoList;
	}

	@Override
	public List<MmdArea> getSonAreaList() {
		return areaDao.getSonAreaList();
	}

	@Override
	public List<MmdArea> getAreaList() {
		return areaDao.getAreaList();
	}
}
